# coding = utf-8

'''
分析肿瘤个数的相关算法
'''

import os
import numpy as np
import matplotlib.pyplot as plt
import cv2
from scipy import ndimage
from skimage import measure
import prettytable as pt

import SimpleITK as sitk

def count_tumor():
    path = "/datasets/DongbeiDaxue/chengkunv2/case_00000/segmentation"
    for item in sorted(os.listdir(path)):
        file_name = os.path.join(path, item)
        data = np.load(file_name)
        if np.max(data) < 2:
            continue
        data[data == 1] = 0
        data[data == 2] = 1
        sum_data = data.sum()
        label_copy = data * 255
        label_copy = label_copy.astype(np.uint8)
        contours, _ = cv2.findContours(label_copy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        tumor_number = len(contours)
        weight = np.ones(data.shape)
        weight = weight * (1-data)
        print(sum_data, tumor_number)
        for counter in contours:
            data_list = []
            for t in range(counter.shape[0]):
                j = counter[t][0]
                data_list.append(j)
            rect = cv2.minAreaRect(np.array([data_list], np.int32))
            box =  cv2.boxPoints(rect)   # 获取最小外接矩形的4个顶点坐标(ps: cv2.boxPoints(rect) for OpenCV 3.x)
            box = np.int0(box)
            temp = np.zeros(label_copy.shape).astype(np.uint8)
            cv2.fillPoly(temp, [box], 1)

            sum_temp = (temp * data).sum()
            avg_weight = sum_data / (sum_temp * tumor_number)
            weight = weight + (avg_weight * (temp*data))


            #cv2.polylines(label_copy, [box], True, [0, 255, 0], thickness=1)
            #cv2.drawContours(label_copy, [box], 0, (255, 0, 0), 1)

        print(np.unique(weight))
        plt.subplot(1, 2, 1)
        plt.imshow(data, cmap="gray")
        plt.subplot(1, 2, 2)
        plt.imshow(weight, cmap="gray")
        plt.show()


def tumor_analysis():
    data_path = "/datasets/DongbeiDaxue/chengkun_only_liver"
    size_100w = []
    size_10w = []
    size_1w = []
    size_1k = []
    size_small = []

    for i in range(80):
        case_id = "case_{}".format(str(i).zfill(5))
        case_path = os.path.join(data_path, case_id)
        segmentation_path = os.path.join(case_path, "segmentation")
        tumor_size = 0
        for item in os.listdir(segmentation_path):
            item_path = os.path.join(segmentation_path, item)
            data = np.load(item_path)
            data[data == 1] = 0
            data[data == 2] = 1
            tumor_size += data.sum()
        print(i, tumor_size)
        if tumor_size >= 1000000:
            size_100w.append(i)
        elif tumor_size >= 100000:
            size_10w.append(i)
        elif tumor_size >= 10000:
            size_1w.append(i)
        elif tumor_size >= 1000:
            size_1k.append(i)
        elif tumor_size < 1000:
            size_small.append(i)

    print(len(size_100w), size_100w)
    print(len(size_10w), size_10w)
    print(len(size_1w), size_1w)
    print(len(size_1k), size_1k)
    print(len(size_small), size_small)

#获取肿瘤数量的真实大小
def get_tumor_count_v2():
    data_path = "E:\Dataset\chengkunv2"
    count_list = []
    for i in range(80):
        case_id = "case_{}".format(str(i).zfill(5))
        case_path = os.path.join(data_path, case_id)
        case_path = os.path.join(case_path, "segmentation")
        np_data = []
        for item in sorted(os.listdir(case_path)):
            item_file = os.path.join(case_path, item)
            data = np.load(item_file)
            np_data.append(data)
        np_data = np.array(np_data)
        np_data[np_data == 1] = 0
        np_data[np_data == 2] = 1

        print("*"*35, case_id, "*"*35)
        [tumor_labels, num] = measure.label(np_data, return_num=True)
        print("tumor size:", np_data.sum())
        print("image shape:", np_data.shape)
        print("tumor count:", num)
        region = measure.regionprops(tumor_labels)

        tb = pt.PrettyTable()
        tb.field_names = ["tumor NO.", "tumor size", "slice begin", "slice end", "total slice", "avg per slice"]
        for j in range(num):
            tb.add_row([
                j, region[j].area, region[j].bbox[0], region[j].bbox[3], region[j].bbox[3] - region[j].bbox[0],
                int(region[j].area / (region[j].bbox[3] - region[j].bbox[0]))]
            )
            count_list.append(int(region[j].area / (region[j].bbox[3] - region[j].bbox[0])))
        print(tb)
        print()

    print(len(count_list))
    print(count_list)



#单一case的分析
def single_case_analysis():
    data_path = "E:\Dataset\chengkunv2\\case_00004\\segmentation"
    np_data = []
    for item in sorted(os.listdir(data_path)):
        item_file = os.path.join(data_path, item)
        data = np.load(item_file)
        np_data.append(data)
    np_data = np.array(np_data)
    #np_data[np_data == 1] = 0
    #np_data[np_data == 2] = 1

    temp = np_data[110]
    print(np.unique(temp))

    #data_path = "E:\Dataset\Liver\qiye\DongBeiDaXue\lesion"
    #case_list = sorted(os.listdir(data_path))
    #case = case_list[62]
    #case_file = os.path.join(data_path, case)
    #data = sitk.GetArrayFromImage(sitk.ReadImage(case_file))
    #data = data[124]




    #plt.subplot(1, 2, 1)
    plt.imshow(temp, cmap="gray")
    #plt.subplot(1, 2, 2)
    #plt.imshow(data, cmap="gray")
    plt.show()


def analysis_tumor_size():
    tumor = [7682, 1, 1, 1, 6, 2, 1, 2, 1, 1, 1, 3, 1, 1, 3039, 32, 4650, 24, 31, 352, 4388, 36, 66, 29, 27, 18, 12, 19, 37, 11, 20, 138, 41, 46, 21, 20, 3909, 22, 34, 34, 60, 17, 5650, 41, 50, 10, 17, 38, 14, 29, 4656, 33, 64, 29, 14, 28, 42, 44, 57, 48, 16, 51, 3, 1, 1, 1, 2, 5, 3, 1, 1, 2, 1, 1, 1, 1, 1, 6305, 16, 267, 14, 35, 16, 25, 128, 16, 7, 16, 17, 53, 67, 231, 137, 77, 155, 21, 333, 1539, 467, 194, 39, 9, 47, 44, 12, 8, 12, 19, 91, 19, 38, 6, 43, 19, 21, 4, 15, 47, 9, 8, 13, 9, 143, 30, 5, 463, 26, 2, 77, 21, 40, 31, 41, 36, 3, 86, 54, 44, 6, 1, 15, 57, 4, 222, 60, 32, 16, 16, 21, 3, 22, 11, 55, 12, 40, 32, 50, 22, 43, 27, 37, 25, 34, 4, 22, 1, 82, 36, 47, 3, 35, 52, 63, 35, 23, 45, 61, 39, 3, 1, 22, 44, 51, 28, 13, 24, 26, 25, 27, 33, 47, 39, 174, 663, 19, 42, 19, 634, 49, 25, 2475, 34, 145, 28, 4174, 6290, 4380, 7, 9506, 822, 8743, 12711, 10285, 8408, 256, 200, 78, 17, 11361, 17, 74, 21, 21, 71, 90, 92, 119, 226, 36, 65, 74, 18, 30, 74, 51, 54, 54, 27, 204, 20, 8, 1192, 41, 73, 109, 88, 65, 115, 159, 93, 236, 2094, 116, 18493, 39, 135, 852, 369, 115, 248, 57, 540, 21, 4435, 19, 104, 10, 477, 7, 7, 5, 5, 5, 5, 5833, 102, 14, 19, 26, 24, 47, 42, 67, 90, 24, 88, 4044, 23, 69, 33, 65, 61, 26, 27, 42, 30, 67, 22, 19, 22, 35, 25, 46, 33, 217, 34, 30, 35, 177, 68, 74, 27, 22, 54, 44, 104, 163, 30, 25, 34, 45, 65, 344, 52, 55, 32, 190, 17, 37, 41, 40, 30, 11, 60, 46, 45, 41, 44, 65, 38, 54, 285, 67, 81, 40, 90, 73, 73, 101, 422, 30, 182, 55, 49, 205, 91, 608, 443, 17, 108, 140, 15, 54, 15, 227, 16819, 13, 22, 40, 57, 26, 60, 23, 24, 31, 24, 40, 3205, 27, 43, 175, 134, 10, 40, 46, 29, 87, 29, 45, 81, 62, 53, 76, 36, 63, 41, 22, 18, 23, 3136, 77, 49, 26, 110, 18436, 38, 32, 30, 601, 52, 23, 29, 27, 17, 27, 10559, 13, 4, 307, 321, 38, 22, 40, 2691, 25, 16, 25, 17, 40, 42, 34, 64, 728, 48, 18, 29, 37, 19, 26, 1874, 28, 46, 22, 1118, 131, 316, 82, 23, 27, 19, 102, 1967, 5057, 4351, 62, 857, 248, 189, 181, 104, 2730, 114, 247, 656, 239, 146, 23, 2695, 15163, 44, 411, 23, 1519, 48, 11, 69, 67, 1557, 60, 253, 504, 32, 17, 19, 44, 53, 20, 310, 15, 46, 34, 23, 29, 18, 5483, 12, 6, 38, 24, 13, 52, 21, 21, 13191, 24, 42, 29, 30, 36, 17, 61, 55, 86, 32, 60, 33, 24, 8, 12, 18, 4381, 75, 1798, 6036, 6435, 3948, 62, 10782, 27, 314, 524, 1015, 130, 392, 1172, 329, 24901, 329, 218, 127, 9677, 32, 22, 9, 29, 43, 15, 39, 23, 7, 8, 126, 87, 141, 4730, 13, 215, 18, 408, 39, 14, 13, 22, 36, 20, 19, 23, 21, 26, 10, 20, 1291, 78, 150, 57, 152, 50, 173, 41, 29, 29, 54, 26, 17, 98, 5336, 10, 6, 8, 223, 145, 171, 20, 221, 83, 266, 239, 91, 15]
    tumor_0_10 = 0
    tumor_10_20 = 0
    tumor_20_50 = 0
    tumor_50_100 = 0
    tumor_100_500 = 0
    tumor_500= 0

    for item in tumor:
        if item <= 10:
            tumor_0_10 += 1
        elif item <= 20:
            tumor_10_20 += 1
        elif item <= 50:
            tumor_20_50 += 1
        elif item <= 100:
            tumor_50_100 += 1
        elif item <= 500:
            tumor_100_500 += 1
        else:
            tumor_500 += 1

    tb = pt.PrettyTable()
    tb.field_names = ["0-10", "10-20", "20-50", "50-100", "100-500", "500+"]
    tb.add_row([tumor_0_10, tumor_10_20, tumor_20_50, tumor_50_100, tumor_100_500, tumor_500])
    tb.add_row([tumor_0_10/len(tumor), tumor_10_20/len(tumor), tumor_20_50/len(tumor), tumor_50_100/len(tumor),
                tumor_100_500/len(tumor), tumor_500/len(tumor)])
    print(tb)

def single_case_tumor_count():
    data_path = "E:\Dataset\chengkunv2"
    for i in range(80):
        case_id = "case_{}".format(str(i).zfill(5))
        case_path = os.path.join(data_path, case_id)
        case_path = os.path.join(case_path, "segmentation")
        np_data = []
        for item in sorted(os.listdir(case_path)):
            item_file = os.path.join(case_path, item)
            data = np.load(item_file)
            np_data.append(data)
        np_data = np.array(np_data)
        np_data[np_data == 1] = 0
        np_data[np_data == 2] = 1

        print("*" * 35, case_id, "*" * 35)
        [tumor_labels, num] = measure.label(np_data, return_num=True)
        print("tumor size:", np_data.sum())
        print("image shape:", np_data.shape)
        print("tumor count:", num)
        region = measure.regionprops(tumor_labels)

        for i in range(num):
            print(region[i].area, region[i].bbox, len(region[i].coords))

        break

if __name__ == '__main__':
    single_case_analysis()